<template>
  <div class="box">
    <div v-if="list.length<6">
      <van-uploader :after-read="afterRead" />
    </div>

    <draggable
      style="word-wrap: break-word; display: flex"
      class="dragArea list-group w-full"
      :list="list"
      @change="log"
    >
      <div
        class="list-group-item bg-gray-300 m-1 p-3 rounded-md text-center"
        v-for="(element,index) in list"
        :key="element"
      >
        <img :src="element" alt="" />
        <button class="delete_img" @click="delete_img(index)">X</button>
      </div>
    </draggable>
  </div>
</template>

<script>
import { defineComponent } from 'vue'
import { VueDraggableNext } from 'vue-draggable-next'

export default defineComponent({
  components: {
    draggable: VueDraggableNext,
  },
  data() {
    return {
      enabled: true,
      list: [],
      dragging: false,
    }
  },
  methods: {
    afterRead(file) {
      console.log(file.objectUrl)
      // 创建FileReader读取文件内容并转换为Data URL格式
      const reader = new FileReader()
      reader.readAsDataURL(file.file)
      reader.onload = (e) => {
        const dataUrl = e.target.result
        this.list = [...this.list, dataUrl]
        // 将更新后的list数据保存到localStorage，转换为JSON字符串格式存储
        localStorage.setItem('list_img', JSON.stringify(this.list))
        this.list = JSON.parse(localStorage.getItem('list_img'))
      }
    },
    log(event) {
      console.log(event)
    },
    // 点击删除按钮
    delete_img(index) {
      this.list.splice(index, 1)
      // 更新本地存储中的数据，保存最新的list
      localStorage.setItem('list_img', JSON.stringify(this.list))
    },

  },
})
</script>
<style scoped lang="scss">
.box {
  height: 400px;
  width: 750px;
  /* background-color: aqua; */
  display: flex;
}
.box img {
  width: 170px;
  height: 160px;
  margin-left: 5px;
}
.list-group-item.bg-gray-300.m-1.p-3.rounded-md.text-center{
  position: relative;

}

.box {
  height: 200px;
  width: 375px;
  /* background-color: aqua; */
  display: flex;
}
.box img {
  width: 85px;
  height: 80px;
  margin-left: 2.5px;
}
.list-group-item.bg-gray-300.m-1.p-3.rounded-md.text-center{
  position: relative;
}

.dragArea.list-group.w-full{
  height: 85px;
  display: flex;
  flex-wrap: wrap;
}

.delete_img{
  width: 20px;
  height: 20px;
  background-color: rgba(254, 250, 250, 0.5);
  position:absolute;
  right: 0;
  border: none;
  border-radius: 0% 0% 0% 100%;
}

.i.van-badge.wrapper.van-icon.van-icon-photograph.van-uploader.upload-icon {
  top: 50%;
  left: 50%;
  font-size: 25px;
}

.van-uploader__input{
  width: 85px;
  height: 80px;
}
</style>
